package cool.doudou.doudada.wechat.core.helper;

import cool.doudou.doudada.wechat.core.entity.xml.msg.ImgTextArticle;
import cool.doudou.doudada.wechat.core.entity.xml.msg.ImgTextItem;
import cool.doudou.doudada.wechat.core.entity.xml.msg.ImgTextMsg;
import cool.doudou.doudada.wechat.core.entity.xml.msg.TextMsg;
import cool.doudou.doudada.wechat.core.util.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * ReplyMsgHelper
 *
 * @author jiangcs
 * @since 2022/08/13
 */
@Slf4j
public class ReplyMsgHelper {
    /**
     * 通用回复
     *
     * @param content 内容
     */
    public void ok(String content) {
        write(content);
    }

    /**
     * 回复 文本消息
     *
     * @param fromUserName 开发者微信号
     * @param toUserName   接收方帐号（收到的OpenID）
     * @param content      文本内容
     */
    public void text(String fromUserName, String toUserName, String content) {
        try {
            TextMsg textMsg = new TextMsg();
            textMsg.setFromUserName(fromUserName);
            textMsg.setToUserName(toUserName);
            textMsg.setCreateTime(System.currentTimeMillis());
            textMsg.setMsgType("text");
            textMsg.setContent(content);
            write(XmlUtil.marshal(textMsg, TextMsg.class));
            log.info("回复文本消息成功：{}", fromUserName);
        } catch (Exception e) {
            log.error("回复文本消息异常", e);
        }
    }

    /**
     * 回复 图文消息
     *
     * @param fromUserName 开发者微信号
     * @param toUserName   接收方帐号（收到的OpenID）
     * @param articleList  图文列表
     */
    public void imgText(String fromUserName, String toUserName, List<Map<String, String>> articleList) {
        try {
            ImgTextMsg imgTextMsg = new ImgTextMsg();
            imgTextMsg.setFromUserName(fromUserName);
            imgTextMsg.setToUserName(toUserName);
            imgTextMsg.setCreateTime(System.currentTimeMillis());
            imgTextMsg.setMsgType("news");
            imgTextMsg.setArticleCount(articleList.size());

            ImgTextItem imgTextItem = new ImgTextItem();
            ImgTextArticle imgTextArticle;
            for (Map<String, String> article : articleList) {
                imgTextArticle = new ImgTextArticle();
                imgTextArticle.setTitle(article.get("title"));
                imgTextArticle.setDescription(article.get("description"));
                imgTextArticle.setPicUrl(article.get("picUrl"));
                imgTextArticle.setUrl(article.get("url"));
                imgTextItem.add(imgTextArticle);
            }
            imgTextMsg.setImgTextItem(imgTextItem);
            write(XmlUtil.marshal(imgTextMsg, ImgTextMsg.class));
            log.info("回复图文消息成功：{}", toUserName);
        } catch (Exception e) {
            log.error("回复图文消息异常", e);
        }
    }

    /**
     * 写入 请求客户端数据
     *
     * @param content 文本内容
     */
    private void write(String content) {
        Writer writer = null;
        try {
            HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
            assert response != null;
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            writer = response.getWriter();
            writer.write(content);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
